package com.shigu.mo.utils;

import com.alibaba.fastjson.JSONObject;
import com.shigu.main4.tools.OssIO;
import com.shigu.mo.exceptions.MoException;
import com.shigu.mo.vo.BodyIDOCR;
import com.shigu.mo.vo.CardOCR;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class CardOcrUtil {

    @Value("${ocr.bodyId_appcode}")
    private String bodyIdAppcode;
    @Value("${ocr.blank_appcode}")
    private String blankAppcode;
    @Autowired
    private OssIO ossIO;
    private final String ID_PATH="idcard/";
    private final String BLANK_PATH="blankcard/";

    /**
     *
     * 身份证识别
     *
     * 误用银行卡的情况
     * {"outputs":[{"outputLabel":"ocr_idcard","outputMulti":{},"outputValue":{"dataType":50,"dataValue":"{\"address\":\"\",
     * \"birth\":\"85809805\",\"config_str\":\"{\\\"side\\\":\\\"face\\\"}\",\"face_rect\":{\"angle\":0,\"center\":{\"x\":0,
     * \"y\":0},\"size\":{\"height\":0,\"width\":0}},\"name\":\"\",\"nationality\":\"汉\",\"num\":\"X90983858098052371\",
     * \"request_id\":\"20171120121746_6bc182f279d75baf50b7bd65cd9a4dfc\",\"sex\":\"男\",\"success\":true}"}}]}
     *
     * {"outputs":[{"outputLabel":"ocr_idcard","outputMulti":{},"outputValue":{"dataType":50,"dataValue":"{\"address\":
     * \"浙江省温岭市温峤镇兴昌路17幢39号\",\"birth\":\"19890512\",\"config_str\":\"{\\\"side\\\":\\\"face\\\"}\",
     * \"face_rect\":{\"angle\":-90,\"center\":{\"x\":973.5,\"y\":487.9998779296875},\"size\":{\"height\":234.99996948242188,
     * \"width\":213.99996948242188}},\"name\":\"赵洪波\",\"nationality\":\"汉\",\"num\":\"331081198905122419\",\"request_id\":
     * \"20171120123843_d22b3ae41ecec1dfba140c711813e101\",\"sex\":\"男\",\"success\":true}"}}]}
     *
     * 检测不到直接报错
     *
     * @param imgbase64
     * @return
     */
    public BodyIDOCR bodayIDCard(Long userId, String imgbase64) throws MoException {
        String host = "https://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + bodyIdAppcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        if (imgbase64.contains("data:image/jpeg;base64,")) {
            imgbase64=imgbase64.replace("data:image/jpeg;base64,","");
        }
        Map<String, String> querys = new HashMap<String, String>();
        String bodys = "{\"inputs\": [{\"image\": {\"dataType\": 50,\"dataValue\": " +
                "\"" +imgbase64+
                "\"}" +
                ",\"configure\": {\"dataType\": 50,\"dataValue\": \"{\\\"side\\\":\\\"face\\\"}\"  }}]}";
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            JSONObject obj=JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            JSONObject dataValue=obj.getJSONArray("outputs").getJSONObject(0).getJSONObject("outputValue").getJSONObject("dataValue");
            BodyIDOCR vo=new BodyIDOCR();
            vo.setBirth(dataValue.getString("birth"));
            vo.setLocation(dataValue.getString("address"));
            vo.setName(dataValue.getString("name"));
            vo.setNationality(dataValue.getString("nationality"));
            vo.setNumber(dataValue.getString("num"));
            vo.setSex(dataValue.getString("sex"));
            //开始保存图片到oss
//            ossIO.uploadFile(Base64Util.)
            String filePath=ID_PATH+userId+"/"+new Date().getTime()+".jpg";
            ossIO.uploadFile(Base64Util.generateImageByte(imgbase64),filePath);
            vo.setImgUrl(ossIO.getDomain()+filePath);
            return vo;
        } catch (Exception e) {
            throw new MoException(e.getMessage());
        }
    }

    /**
     * 银行卡
     * {"outputs": [{
     "outputLabel": "ocr_bank_card",
     "outputMulti": {},
     "outputValue": {
     "dataType": 50,
     "dataValue": "{\"card_num\":\"6226227701770418\",\"request_id\":\"20171120112225_eff2af70bae6274f34b7002da025dc47\",\"success\":true}"}}]}

     {"outputs": [{
     "outputLabel": "ocr_bank_card",
     "outputMulti": {},
     "outputValue": {
     "dataType": 50,
     "dataValue": "{\"err_msg\":\"Failed to parse bank card number\",\"request_id\":\"20171120112530_72a4344aded901f6e2bfd1e22b128fe4\",\"success\":true}"}}]}
     * @param imgbase64
     * @return
     */
    public CardOCR blankCard(String imgbase64,Long userId) throws MoException {
        if (imgbase64 == null) {
            throw new MoException("base64数据异常");
        }
        if (imgbase64.contains("data:image/jpeg;base64,")) {
            imgbase64=imgbase64.replace("data:image/jpeg;base64,","");
        }
        String host = "http://yhk.market.alicloudapi.com";
        String path = "/rest/160601/ocr/ocr_bank_card.json";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + blankAppcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        StringBuffer sb=new StringBuffer();
        sb.append("{\"inputs\": [{\"image\": {\"dataType\": 50,\"dataValue\": \"");
        sb.append(imgbase64);
        sb.append("\"}}]}");
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, sb.toString());
            //获取response的body
            JSONObject obj=JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            JSONObject dataValue=obj.getJSONArray("outputs").getJSONObject(0).getJSONObject("outputValue").getJSONObject("dataValue");
            CardOCR vo=new CardOCR();
            vo.setCardNum(dataValue.getString("card_num"));
            String filePath=BLANK_PATH+userId+"/"+new Date().getTime()+".jpg";
            vo.setImgUrl(ossIO.uploadFile(Base64Util.generateImageByte(imgbase64),filePath));
            return vo;
        } catch (Exception e) {
            throw new MoException(e.getMessage());
        }
    }
}
